#coding:UTF-8

import requests
import request
import json
import re
import sys 

"""获取歌曲"""
def get_song(x, num):
    url = "https://songsearch.kugou.com/song_search_v2?callback=jQuery112408817511193234773_1579498086701&keyword={}"\
    "&page=1&pagesize=30&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&"\
    "privilege_filter=0&_=1547710455016".format(x)
    res = requests.get(url).text

    js = json.loads(res[res.index('(') + 1:-2])

    data = js['data']['lists']


    try:
        for i in range(int(num)):
            print(str(i + 1) + ">>>" + str(data[i]['FileName']).replace('<em>', '').replace('</em>', ''))
        number = int(input("\nPlease enter the serial number of the song to be downloaded (enter -1 to exit the program): "))
        if number == -1:
            exit()
        else:
            name = str(data[number - 1]['FileName']).replace('<em>', '').replace('</em>', '')
            fhash = data[number - 1]['FileHash']
            album_id = data[number - 1]['AlbumID']

            hash_url = "https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery1910426146317505981_1579498907434&hash="+fhash+"&album_id="+album_id+"&dfid=0PR1Sj0vz45v0fJu8Y2cS4tj&mid=f99e05a7db11f2cbe44fe0283c4869ee&platid=4&_=1579498907435"
            header={
            "Host":"www.xxx.com",
            "Referer":"http://www.xxx.com/xxx.html?199",
            "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36"

            }
            print(hash_url)
#             hash_content = requests.get(hash_url, headers = header, proxies=getIp()).text
            hash_content = requests.get(hash_url).text
            hash_content = json.loads(hash_content[hash_content.index('(') + 1:-2])
            if hash_content['status'] == 0:
                print(hash_content)
                hash_content = requests.get(hash_url, headers = header, proxies=getIp()).text
                exit()
            else:
                play_data = hash_content['data']

            # 获得下载链接
#             play_url = ''.join(re.findall('"play_url":"(.*?)"', hash_content))#以''链接成新的字符串
            real_download_url = play_data['play_url']
#             real_download_url = play_url.replace("\\", "")
            if real_download_url:
                f = open('/home/syy/音乐/music/%s.mp3'%(name), "wb")
                f.write(requests.get(real_download_url).content)

                if play_data['lyrics']:
                    word = re.sub("[A-Za-z0-9\$\[\]\.\:]", "", play_data['lyrics'])
                    with open('/home/syy/音乐/music/%s'%(name) + ".txt", "w")as fp:
                       fp.write(word)
            else:
                print(real_download_url)
                exit()
                pass

            print("The song has been downloaded!")
    except Exception as e:
        raise

def getIp():
    ip = '200.69.181.74'
    port = '8080'
    ip_data = {
        "http": ip + ":" + port
    }
    return ip_data



if __name__ == '__main__':
    x = input("Please enter the title of the song：")
    num = input("Please enter the number of songs:")
    get_song(x, num)
